package br.unisul.prolinear.utils;

import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private static SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
	private static final ThreadLocal<Session> sessionThread = new ThreadLocal<Session>();
	private static final ThreadLocal<Transaction> transactionThread = new ThreadLocal<Transaction>();


	private static SessionFactory getSessionFactory()  throws MappingException	{	
		return sessionFactory;
	}

	public static Session getSession()	{
		Session s =  sessionThread.get();
		if(s == null){
			s = getSessionFactory().openSession();
			sessionThread.set(s);
		}
		return s;
	}

	public static void closeSession() {
		Session session =  sessionThread.get();
		if ((session != null) && (session.isOpen())) {
			sessionThread.set(null);
			session.close();
		}
	}

	public static void beginTransaction() {
		transactionThread.set(getSession().beginTransaction());
	}

	public static void commitTransaction() {
		Transaction transaction = (Transaction) transactionThread.get();
		if ((transaction != null) && (!(transaction.wasCommitted())) && (!(transaction.wasRolledBack()))) {
			transaction.commit();
			transactionThread.set(null);
			closeSession();
		}		
	}

	public static void rollbackTransaction() {
		Transaction transaction = (Transaction) transactionThread.get();
		if ((transaction != null) && (!(transaction. wasCommitted())) && (!(transaction.wasRolledBack()))) {
			transaction.rollback();
			transactionThread.set(null);
			closeSession();
		}
	}



}


